package org.wizehack.mri;

import org.wizehack.mri.fl.SFLAlgorithm;
import org.wizehack.mri.repo.MongoDBAccessPoint;

import com.mongodb.DBCursor;
import com.mongodb.DBObject;

class BugAnalysisThread implements Runnable {

	private SFLAlgorithm algorithm;
	private int[] totalPassed;
	private int[] totalFailed;
	private int testSuite;
	private boolean[][] isPassed;
	private String sourceCodeId;
//	private String code;
//	private int number;
	
	private MongoDBAccessPoint dbap = MongoDBAccessPoint.getInstance();
	
	public BugAnalysisThread(SFLAlgorithm algorithm,
			int[] totalPassed, int[] totalFailed, int testSuite,
			boolean[][] isPassed, String sourceCodeId) {
	
		this.algorithm = algorithm;
		this.totalPassed = totalPassed;
		this.totalFailed = totalFailed;
		this.testSuite = testSuite;
		this.isPassed = isPassed;
		this.sourceCodeId = sourceCodeId;
//		this.code = code;
//		this.number = number;
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		DBCursor covCursor = dbap.getDocumentsFromCoverage(sourceCodeId, testSuite);
		int passed = 0;
		int failed = 0;
		double sus = 0;
		String file = null;
		String code = null;
		int number = 0;
		if(covCursor != null){
			try{
				
				while(covCursor.hasNext()){

					DBObject covDBObj = covCursor.next();

					int testCase = (int) covDBObj.get("test_case")-1;
					file = covDBObj.get("file_name").toString();
					code = covDBObj.get("code").toString();
					number = (int) covDBObj.get("number");
					
					if(isPassed[testSuite-1][testCase]){
						passed++;
					} else {
						failed++;
					}
				}//end while
										
				sus = algorithm.getSuspiciousness(totalPassed[testSuite-1], totalFailed[testSuite-1], passed, failed);
				/*
				if(file.indexOf("EditorActions.java")>0){
					if(number > 450 && number < 480){
						System.out.println("suspiciousness: " + number + " : " + sus);
					}
				}
				*/
				if(sus > 0) { 				// sus 입력					
					dbap.insertDataToSuspiciousness(file, sourceCodeId.toString(), code, number, testSuite, sus);
				}				
				
			} finally {
				covCursor.close();
			}
		} //end if
	}

}
